package io.renren.modules.generator.controller;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.renren.common.enums.FileStatus;
import io.renren.common.exception.RRException;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.generator.entity.FileEntity;
import io.renren.modules.generator.service.FileService;
import io.renren.modules.generator.vo.RecycleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.generator.entity.MkdirEntity;
import io.renren.modules.generator.service.MkdirService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;


/**
 * @author jianzhen
 * @email sunlightcs@gmail.com
 * @date 2022-03-14 22:03:11
 */
@RestController
@RequestMapping("generator/mkdir")
@Transactional
public class MkdirController {
    @Autowired
    private MkdirService mkdirService;

    @Autowired
    private FileService fileService;

    /**
     * 文件夹列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = mkdirService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{dirId}")
    public R info(@PathVariable("dirId") Integer dirId) {
        MkdirEntity mkdir = mkdirService.getById(dirId);

        return R.ok().put("mkdir", mkdir);
    }

    /**
     * 新建文件夹
     */
    @RequestMapping("/save")
    public R save(@RequestBody MkdirEntity mkdir) {

        mkdirService.saveDir(mkdir);

        return R.ok();
    }

    /**
     * 重命名
     */
    @RequestMapping("/update")
    public R update(@RequestBody MkdirEntity mkdir) {
        mkdirService.updateDir(mkdir);

        return R.ok();
    }

    /**
     * 清空回收站文件夹
     */
    @RequestMapping("/clear/{id}")
    public R clear(@PathVariable("id") Integer dirId) {
        mkdirService.deleteDir(dirId);

        return R.ok();
    }

    /**
     * 删除文件夹
     */
    @RequestMapping("/delete/{id}")
    public R delete(@PathVariable("id") Integer dirId) {
        try {
            MkdirEntity mkdirEntity = new MkdirEntity();
            mkdirEntity.setDirId(dirId);
            mkdirEntity.setIsDelete(FileStatus.DELETE.getStatus());
            //设置回收文件夹时间-默认一个月
            Date date = new Date();
            //创建Calendar实例
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);   //设置当前时间
            //同理增加一个月和一天的方法：
            cal.add(Calendar.MONTH, 1);
            mkdirEntity.setDeleteTime(cal.getTime());
            mkdirService.updateById(mkdirEntity);
            QueryWrapper<FileEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("dir_id", dirId).eq("is_delete", FileStatus.NORMAL.getStatus());
            List<FileEntity> list = fileService.list(wrapper);
            list.forEach(file -> {
                UpdateWrapper<FileEntity> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("file_id", file.getFileId());
                updateWrapper.set("is_delete", FileStatus.DELETE.getStatus());
                fileService.update(updateWrapper);
            });
        } catch (Exception e) {
            throw new RRException("文件夹删除失败");
        }

        return R.ok();
    }

    /**
     * 获取所有未删除文件夹
     *
     * @return
     */
    @RequestMapping("/selectAll")
    public R selectAll() {

        List<MkdirEntity> list = mkdirService.selectAll();

        return R.ok().put("mkdir", list);
    }

    /**
     * 获取所属文件夹(不包括自己的文件夹)
     *
     * @return
     */
    @RequestMapping("/getUpDir/{dirId}")
    public R getUpDir(@PathVariable("dirId") Integer dirId) {

        List<MkdirEntity> list = mkdirService.getUpDir(dirId);

        return R.ok().put("mkdir", list);
    }


    /**
     * 取回文件夹
     *
     * @param dirId
     * @return
     */
    @RequestMapping("/reclaim/{id}")
    public R reclaim(@PathVariable("id") Integer dirId) {

        mkdirService.reclaim(dirId);

        return R.ok();
    }

    /**
     * 回收站列表
     */
    @RequestMapping("/deleteList")
    public R deleteList(@RequestParam Map<String, Object> params) {
        //当前用户id
        Long userId = ShiroUtils.getUserId();
        List<RecycleVo> recycleVos = new ArrayList<>();
        List<Integer> fileIds = new ArrayList<>();
        QueryWrapper<MkdirEntity> mkdirWrapper = new QueryWrapper<>();
        mkdirWrapper.select("dir_id", "dir_name", "create_time");
        mkdirWrapper.eq("is_delete", FileStatus.DELETE.getStatus());
        //获取当前用户的回收的文件夹集合
        mkdirWrapper.eq("user_id", userId);
        List<MkdirEntity> mkdirList = mkdirService.list(mkdirWrapper);
        if (mkdirList.size() > 0) {
            for (MkdirEntity mkdirEntity : mkdirList) {
                RecycleVo recycleVo = new RecycleVo();
                Integer dirId = mkdirEntity.getDirId();
                recycleVo.setId(dirId);
                recycleVo.setName(mkdirEntity.getDirName());
                recycleVo.setType(FileStatus.DIR.getStatus());
                recycleVo.setCreateTime(mkdirEntity.getCreateTime());
                recycleVos.add(recycleVo);
                QueryWrapper<FileEntity> fileWrapper = new QueryWrapper<>();
                fileWrapper.select("file_id");
                fileWrapper.eq("dir_id", dirId).eq("is_delete", FileStatus.DELETE.getStatus()).eq("user_id", userId);
                List<FileEntity> fileList = fileService.list(fileWrapper);
                if (fileList.size() > 0) {
                    for (FileEntity fileEntity : fileList) {
                        fileIds.add(fileEntity.getFileId());
                    }
                }

            }
        }
        QueryWrapper<FileEntity> wrapper = new QueryWrapper<>();
        wrapper.select("file_id", "file_name", "create_time");
        wrapper.eq("is_delete", FileStatus.DELETE.getStatus()).eq("user_id", userId);
        List<FileEntity> fileList = fileService.list(wrapper);
        if (fileList.size() > 0) {
            fileList.forEach(file -> {
                if (!fileIds.contains(file.getFileId())) {
                    RecycleVo recycleVo = new RecycleVo();
                    recycleVo.setId(file.getFileId());
                    recycleVo.setName(file.getFileName());
                    recycleVo.setType(FileStatus.FILE.getStatus());
                    recycleVo.setCreateTime(file.getCreateTime());
                    recycleVos.add(recycleVo);
                }
            });
        }
        int pageSize = Integer.parseInt(params.get("limit").toString());
        int currPage = Integer.parseInt(params.get("page").toString());
        int startSize = (currPage - 1) * pageSize;
        int endSize = currPage * pageSize;
        List<RecycleVo> list = new ArrayList<>();
        if (endSize > recycleVos.size()) {
            list = recycleVos.subList(startSize, recycleVos.size());
        } else {
            list = recycleVos.subList(startSize, endSize);
        }
        PageUtils newPage = new PageUtils(list, recycleVos.size(), Integer.parseInt(params.get("limit").toString()), Integer.parseInt(params.get("page").toString()));

        return R.ok().put("page", newPage);
    }


    /**
     * 清空回收站
     */
    @RequestMapping("/clearAll")
    public R clearAll() {
        mkdirService.clearAll();
        return R.ok();
    }

    /**
     * 获取文件夹下文件详情
     *
     * @return
     */
    @RequestMapping("/getDirFile/{dirId}")
    public R getDirFile(@PathVariable("dirId") Integer dirId) {

        List<FileEntity> list = mkdirService.getDirFile(dirId);

        return R.ok().put("file", list);
    }

    /**
     * 定时自动清空回收站
     *
     * @return
     */
    @RequestMapping("/autoClear")
    public R autoClear() {
        mkdirService.autoClear();
        return R.ok();
    }

}
